package com.jt.service;

import com.jt.vo.ImagVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.sound.midi.Soundbank;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@PropertySource("classpath:/image.properties")
public class FileServiceImpl implements FileService{
    @Value("${image.localDir}")
    private String localDir;
    @Value("${image.preUrl}")
    private String preUrl;
/*    private String localDir = "E:/images";
    private String preUrl = "http://image.jt.com";*/


    @Override
    public ImagVO upload(MultipartFile file) {
        //获取图片名称
        String filename = file.getOriginalFilename();
        //利用正则判断类型
        //bug说明：由于Windows不区分大小写所以全部转换成小写
        filename = filename.toLowerCase();
        if (!filename.matches("^.+\\.(jpg|png|gif)$")){
            //如果不正确就返回null
            return null;
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width ==0||height==0){
                //说明文件不是图片
                return null;
            }
            //3.根据时间实现目录的创建 时间--yyyy/MM/dd
            String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            // "E:/images/2021/11/11
            String localDirPath = localDir + dateDir;
            //创建目录
            File dirFile = new File(localDirPath);
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }

            //4、使用uuid替换文件名称（唯一：系统内部唯一）
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //截取文件后缀
            int index = filename.lastIndexOf(".");
            //获取类型 .jpg
            String fileType = filename.substring(index);
            String newFileName = uuid+fileType;
            //5、实现文件上传操作， 目录/文件名称
            String realFilePath = localDirPath+newFileName;
            file.transferTo(new File(realFilePath));
            System.out.println("上传成功");

            //6、封装返回值（时间/uuid.type）
            String virtualPath = dateDir+newFileName;
            //http://image.jt.com/2021/11/11/a12da.png
            String url = preUrl+virtualPath;
            System.out.println("磁盘地址:"+realFilePath);
            System.out.println("网络地址:"+url);
            return new ImagVO(virtualPath,url,newFileName);

        }catch (IOException e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public void deleteFile(String virtualPath) {
        String path = localDir + virtualPath;
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
    }
}
